/**
 * 上传控件整理
 * @author rubekid
 * extendOptions //扩展自定义方法有
 * {
 *     invalidFileTypeError:"上传文件只支持{types}格式", //格式错误提示信息
 *     checkQueue:function(queueData){ //选择文件后队列校验, queueData.queueLength选择的文件队列长度
 *     		if(queueData.queueLength > 10){
 *     			showError("最多上传10张图片");
				return false;	
 *     		}
 *     		return true;
 *     },
 *     afterSuccess:function(result, target){//文件上传成功后回调 result：json格式返回信息，target当前控件对象
 *    		$("#thumbnail").attr("src", result.url);
 *     },
 *     afterComplete:function(uploadedCount, uploadedErrorCount){//全部上传完成后回调
 *          if(uploadedErrorCount==0){ //上传失败格式为0
 *     			showError("上传完成");
 *     		}
 *     }
 *     
 * }
 */
function fileUploadify(selector, extendOptions){
	extendOptions = extendOptions || {};
	var uploadifyEle = selector.get(0);
	var width = selector.outerWidth(false);
	var margin = selector.css("margin");
	if(margin==""){
		var ml = selector.css("marginLeft") || "0px";
		var mt = selector.css("marginTop") || "0px";
		var mr = selector.css("marginRight") || "0px";
		var mb = selector.css("marginBottom") || "0px";
		margin = mt + " " + mr + " " +mb + " " +ml;
	}
	var invalidFileTypeError = extendOptions.invalidFileTypeError||getLanguage('uploadify.error.type',"上传文件只支持{types}格式");
	if(selector.is(":hidden")){//若按钮不可见时宽度获取会有问题
		var clone = selector.clone();
		clone.show();
		$(document.body).append(clone);
		width = clone.outerWidth(false);
		clone.remove();
	}
	var buttonText = selector.text();
	var containeSpace = /\s/.test(buttonText);
	if(containeSpace){
		width +=1;
	}
	
	var options = $.extend({
		fileObjName:"file",
		buttonText: selector.html(),
		swf  : '/script/plugins/uploadify/uploadify.swf',
		fileTypeDesc : '文件',
		fileTypeExts : '*.*',  
		width: width,
		removeTimeout:1,
		overrideEvents  : ['onSelectError', 'onDialogClose'],
        onSelectError:function(file, errorCode, errorMsg){
        	var settings = this.settings;
            var message = extendOptions.message || {};
        	switch(errorCode) {
                case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
                    showError(message.QUEUE_LIMIT_EXCEEDED || getLanguage('uploadify.error.queuesizelimit.1',"一次最多只能上传")+settings.queueSizeLimit+getLanguage('uploadify.error.queuesizelimit.2',"个文件"));
                    break;
                case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                	showError(message.FILE_EXCEEDS_SIZE_LIMIT || getLanguage('uploadify.error.filesizelimit',"文件大小不能超过")+ settings.fileSizeLimit);
                    break;
                case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                	if(file || ""){
                		showError(message.ZERO_BYTE_FILE || getLanguage('uploadify.error.filename.1',"文件 [")+file.name+getLanguage('uploadify.error.filename.2',"] 大小异常！"));
                	} else {
                		showError(message.ZERO_BYTE_FILE || getLanguage('uploadify.error.uploadfail',"文件上传失败，请重试！"));
                	}
                    break;
                case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                	var types = settings.fileTypeExts.replace(/\*/g, '').replace(/;/g, ' ');
                	var message = invalidFileTypeError.replace("{types}", types);
                	showError(message.INVALID_FILETYPE || message);
                    break;
            }
        },
        onDialogOpen : function(){
        	uploadifyEle.uploadedErrorCount = 0;
        	uploadifyEle.uploadedCount = 0;
        },
        onDialogClose : function(filesSelected, filesQueued, queueLength) {
        	$('#' + this.settings.queueID).hide();
        	if( this.queueData.queueLength==0 
        			|| this.queueData.filesErrored > 0
        			|| (typeof extendOptions.checkQueue == "function" && !extendOptions.checkQueue(this.queueData)) ){
        			
        		$('#' + this.settings.id).uploadify('cancel', "*");
				$('#' + this.settings.id).uploadify("stop");
        		return ;
        	}
        	$('#' + this.settings.id).uploadify('disable', true);
        	$('#' + this.settings.queueID).show().css({opacity:1});
		},
		onQueueComplete:function(file){
			$('#' + this.settings.id).uploadify('disable', false);
			$('#' + this.settings.queueID).fadeTo(1000, 0, function(){
				$(this).hide();
				if(typeof extendOptions.afterComplete == "function"){
					extendOptions.afterComplete(uploadifyEle.uploadedCount, uploadifyEle.uploadedErrorCount);
				}
			});
		},
		onUploadSuccess : function(file, result, response) {
			result = $.evalJSON(result);
			var _this = this;
			var settings = this.settings;
        	uploadifyEle.uploadedCount++;
			if(result.type == "failure"){
				uploadifyEle.uploadedErrorCount++;
				showError(result.msg||getLanguage('uploadify.error.uploadfail',"上传文件失败"));
				if(result.errorType =="total_limit"){
					$('#' + settings.id).uploadify("stop");
		            $.each(this.queueData.files, function(){
		            	$("#" + this.id).hide();
		            	$('#' + settings.id).uploadify('cancel', this.id);
		            });
				}
			}else if(typeof extendOptions.afterSuccess == "function"){
				extendOptions.afterSuccess(result, this);
			}
		},
		onInit:function(target){
			var button = $('#' + target.settings.id);
			var buttonText =  button.find('.uploadify-button-text');	
			buttonText.addClass(selector.attr("class"));
			buttonText.css({"margin":"0px"});
			button.css({"margin": margin});

			if(extendOptions.button_disabled){
				$('#' + target.settings.id + '-button').addClass("disabled");
			}
			if(typeof extendOptions.afterInit == "function"){
				extendOptions.afterInit(target.settings);
			}
		}
	}, extendOptions);
	if(BrowserHelper.isChrome){
		setTimeout(function(){
			selector.uploadify(options);
		}, 200);
	}else{
		selector.uploadify(options);
	}
	
	selector.disable = function(){
		selector.uploadify('disable', true);//设置不可用
		selector.uploadify('settings', 'buttonCursor', 'arrow');
	};
	selector.enable = function(){
		selector.uploadify('disable', false);//设置可用
		selector.uploadify('settings', 'buttonCursor', 'hand');
	};
	selector.destroy = function(){
		selector.uploadify("destroy");
	};

	selector.setFormData = function(data){ //设置参数
		selector.uploadify("settings", "formData", data);
	};
	
	return selector;
}

/**
 * 图片上传
 * @see function fileUploadify
 */
function imageUploadify(selector, extendOptions){
	var options = $.extend({
		fileObjName:"image",
		//fileSizeLimit:"2MB",
		queueSizeLimit:1,
		multi:false,
		fileTypeDesc : getLanguage('uploadify.filetypedesc','图片文件'),
		fileTypeExts : '*.jpg;*.jpeg;*.gif;*.bmp;*.png',
		invalidFileTypeError:"上传图片只支持{types}格式",
		height : 35
	}, extendOptions||{});
	console.log(options);
	return fileUploadify(selector, options);
}

/**
 * MP4上传
 * @see function fileUploadify
 */
function mp4Uploadify(selector, extendOptions){
	extendOptions = extendOptions || {};
	var uploadifyEle = selector.get(0);
	var width = selector.outerWidth(false);
	var margin = selector.css("margin");
	if(margin==""){
		var ml = selector.css("marginLeft") || "0px";
		var mt = selector.css("marginTop") || "0px";
		var mr = selector.css("marginRight") || "0px";
		var mb = selector.css("marginBottom") || "0px";
		margin = mt + " " + mr + " " +mb + " " +ml;
	}
	var invalidFileTypeError = extendOptions.invalidFileTypeError||getLanguage('uploadify.error.type',"上传文件只支持{types}格式");
	if(selector.is(":hidden")){//若按钮不可见时宽度获取会有问题
		var clone = selector.clone();
		clone.show();
		$(document.body).append(clone);
		width = clone.outerWidth(false);
		clone.remove();
	}
	var buttonText = selector.text();
	var containeSpace = /\s/.test(buttonText);
	if(containeSpace){
		width +=1;
	}

	var options = $.extend({
		fileObjName:"file",
		buttonText: selector.html(),
		swf  : '/script/plugins/uploadify/uploadify.swf',
		fileTypeDesc : '文件',
		fileTypeExts : '*.mp4',
		width: width,
		removeTimeout:1,
		overrideEvents  : ['onSelectError', 'onDialogClose'],
		onSelectError:function(file, errorCode, errorMsg){
			var settings = this.settings;
			var message = extendOptions.message || {};
			switch(errorCode) {
				case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
					showError(message.QUEUE_LIMIT_EXCEEDED || getLanguage('uploadify.error.queuesizelimit.1',"一次最多只能上传")+settings.queueSizeLimit+getLanguage('uploadify.error.queuesizelimit.2',"个文件"));
					break;
				case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
					showError(message.FILE_EXCEEDS_SIZE_LIMIT || getLanguage('uploadify.error.filesizelimit',"文件大小不能超过")+ settings.fileSizeLimit);
					break;
				case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
					if(file || ""){
						showError(message.ZERO_BYTE_FILE || getLanguage('uploadify.error.filename.1',"文件 [")+file.name+getLanguage('uploadify.error.filename.2',"] 大小异常！"));
					} else {
						showError(message.ZERO_BYTE_FILE || getLanguage('uploadify.error.uploadfail',"文件上传失败，请重试！"));
					}
					break;
				case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
					var types = settings.fileTypeExts.replace(/\*/g, '').replace(/;/g, ' ');
					var message = invalidFileTypeError.replace("{types}", types);
					showError(message.INVALID_FILETYPE || message);
					break;
			}
		},
		onDialogOpen : function(){
			uploadifyEle.uploadedErrorCount = 0;
			uploadifyEle.uploadedCount = 0;
		},
		onDialogClose : function(filesSelected, filesQueued, queueLength) {
			$('#' + this.settings.queueID).hide();
			if( this.queueData.queueLength==0
				|| this.queueData.filesErrored > 0
				|| (typeof extendOptions.checkQueue == "function" && !extendOptions.checkQueue(this.queueData)) ){

				$('#' + this.settings.id).uploadify('cancel', "*");
				$('#' + this.settings.id).uploadify("stop");
				return ;
			}
			$('#' + this.settings.id).uploadify('disable', true);
			$('#' + this.settings.queueID).show().css({opacity:1});
		},
		onQueueComplete:function(file){
			$('#' + this.settings.id).uploadify('disable', false);
			$('#' + this.settings.queueID).fadeTo(1000, 0, function(){
				$(this).hide();
				if(typeof extendOptions.afterComplete == "function"){
					extendOptions.afterComplete(uploadifyEle.uploadedCount, uploadifyEle.uploadedErrorCount);
				}
			});
		},
		onUploadSuccess : function(file, result, response) {
			result = $.evalJSON(result);
			var _this = this;
			var settings = this.settings;
			uploadifyEle.uploadedCount++;
			if(result.type == "failure"){
				uploadifyEle.uploadedErrorCount++;
				showError(result.msg||getLanguage('uploadify.error.uploadfail',"上传文件失败"));
				if(result.errorType =="total_limit"){
					$('#' + settings.id).uploadify("stop");
					$.each(this.queueData.files, function(){
						$("#" + this.id).hide();
						$('#' + settings.id).uploadify('cancel', this.id);
					});
				}
			}else if(typeof extendOptions.afterSuccess == "function"){
				extendOptions.afterSuccess(result, this);
			}
		},
		onInit:function(target){
			var button = $('#' + target.settings.id);
			var buttonText =  button.find('.uploadify-button-text');
			buttonText.addClass(selector.attr("class"));
			buttonText.css({"margin":"0px"});
			button.css({"margin": margin});

			if(extendOptions.button_disabled){
				$('#' + target.settings.id + '-button').addClass("disabled");
			}
			if(typeof extendOptions.afterInit == "function"){
				extendOptions.afterInit(target.settings);
			}
		}
	}, extendOptions);
	if(BrowserHelper.isChrome){
		setTimeout(function(){
			selector.uploadify(options);
		}, 200);
	}else{
		selector.uploadify(options);
	}

	selector.disable = function(){
		selector.uploadify('disable', true);//设置不可用
		selector.uploadify('settings', 'buttonCursor', 'arrow');
	};
	selector.enable = function(){
		selector.uploadify('disable', false);//设置可用
		selector.uploadify('settings', 'buttonCursor', 'hand');
	};
	selector.destroy = function(){
		selector.uploadify("destroy");
	};

	selector.setFormData = function(data){ //设置参数
		selector.uploadify("settings", "formData", data);
	};

	return selector;
}

FlashAlert = false;
/**
 * 检测浏览器是否安装了flash 
 */
function flashChecker(){
		var swf = null;
		if(document.all){
			try{
				swf = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
		    }
		    catch(e){
		        return false;
		    }
		}
		else if(navigator.plugins && navigator.plugins.length > 0){
			swf = navigator.plugins["Shockwave Flash"];
		}

		if(swf){
			return true;	
		}
		return false;
}

(function($){
	// 封装 图片上传功能
	$.fn.imageUploadify = function(options){
		if(!flashChecker() && !FlashAlert){
			$(document.body).append('<div style="z-index:10000;position: fixed;top: 0px; left:50%;	_POSITION: absolute;overflow: hidden; text-align:center; padding:4px 10px; line-height:24px; color:#fff; background:#fe9437;  display:block; border:#e4812a 1px solid; width:360px; border-top:none; margin-left:-160px; font-size:12px;">您还未安装flash，上传功能无法使用</div>');
			FlashAlert = true;
			return null;
		}
		var _this = $(this);
		require(["css!/script/plugins/uploadify/uploadify.css","jquery.json"],function(){
			require(["/script/plugins/uploadify/jquery.uploadify.js"],function(){
				return imageUploadify(_this,options);
			});
		});
	};
	
	// 封装文件上传功能
	$.fn.fileUploadify = function(options){
		if(!flashChecker() && !FlashAlert){
			$(document.body).append('<div style="z-index:10000;position: fixed;top: 0px; left:50%;	_POSITION: absolute;overflow: hidden; text-align:center; padding:4px 10px; line-height:24px; color:#fff; background:#fe9437;  display:block; border:#e4812a 1px solid; width:360px; border-top:none; margin-left:-160px; font-size:12px;">您还未安装flash，上传功能无法使用</div>');
			return null;
		}
		var _this = $(this);
		require(["css!/script/plugins/uploadify/uploadify.css","jquery.json"],function(){
			require(["/script/plugins/uploadify/jquery.uploadify.js"],function(){
				return fileUploadify(_this,options);
			});
		});
	};

	// 封装mp4文件上传功能
	$.fn.mp4Uploadify = function(options){
		if(!flashChecker() && !FlashAlert){
			$(document.body).append('<div style="z-index:10000;position: fixed;top: 0px; left:50%;	_POSITION: absolute;overflow: hidden; text-align:center; padding:4px 10px; line-height:24px; color:#fff; background:#fe9437;  display:block; border:#e4812a 1px solid; width:360px; border-top:none; margin-left:-160px; font-size:12px;">您还未安装flash，上传功能无法使用</div>');
			return null;
		}
		var _this = $(this);
		require(["css!/script/plugins/uploadify/uploadify.css","jquery.json"],function(){
			require(["/script/plugins/uploadify/jquery.uploadify.js"],function(){
				return mp4Uploadify(_this,options);
			});
		});
	};
})(jQuery);
